package com.skstudio.nuprint.view;

import java.io.File;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Handler;

public class PsParser {
	static {
        System.loadLibrary("psparser");
    }
	
	Context mCtx;
	
	ParserEventListener mListener = null;
	
	Handler mHandler = new Handler();
	
	public PsParser(Context ctx, ParserEventListener listener) {
		mCtx = ctx;
		mListener = listener;
	}
	
	public interface ParserEventListener {
		public void onFileLoaded();
		
		public void onPageRendered(int pageNo, Bitmap bmp);
	}
	
	protected native long nativeOpen(String path);

	protected native void nativeClose(long handle);
	
	protected native long nativeGetPageCount(long handle);

	protected native long nativeGetPageWidth(long handle, long pageNo);
	
	protected native long nativeGetPageHeight(long handle, long pageNo);
	
	protected native Bitmap nativeRenderPage(long handle, long pageNo, float scale);
	
	File mFile = null;
	
	long mPsHandle = -1, mPageCount = 0, mCurrPageNo = 0;
	
	public void openFile(File file) {
		mFile = file;
		
		new Thread(new Runnable(){
			@Override
			public void run() {
				mPsHandle = nativeOpen(mFile.getAbsolutePath());
				mPageCount = nativeGetPageCount(mPsHandle);
				
				mHandler.post(new Runnable() {
					@Override
					public void run() {
						mListener.onFileLoaded();
					}
				});	
			}
		
		}).start();
	}
	
	public void closeFile() {
		if (mPsHandle == -1) return;
		
		nativeClose(mPsHandle);
	}
	
	public long getPageCount() {
		if (mPsHandle == -1) return -1;
		
		return nativeGetPageCount(mPsHandle);
	}
	
	public void renderPage(final long pageNo) {
		if (mPsHandle == -1) return;
		
		new Thread(new Runnable(){
			@Override
			public void run() {
				final Bitmap bm = nativeRenderPage(mPsHandle, pageNo, 1.0f);
				
				mHandler.post(new Runnable() {
					@Override
					public void run() {
						mListener.onPageRendered(pageNo, bm);
					}
				});	
			}
		}).start();
	}
}
